<?php
namespace pays;
class RefundOrder
{
    //微信退款
    public function wechat_refund($order_sn,$amount,$amount1){
        $wxconfig = \addons\epay\library\Service::getConfig('wechat');
        $params = [
            "order_sn"=>$order_sn,//商城订单号
            "total_fee"=>$amount,//订单实际支付金额
            "refund_fee"=>$amount1,//需要退款金额
        ];
        $config = [
            'app_id'=>$wxconfig['appid'],
            'mch_id'=>$wxconfig['mch_id'],
            'api_key'=>$wxconfig['key'],
            'sign_type'=>'MD5',
        ];
        $driver = new \pays\PayApi($config);
        $refund = $driver->gateway("wechatpay")->refund($params);
        var_dump($refund);exit;
        if($refund["return_code"] == "SUCCESS" && $refund["result_code"] == "SUCCESS"){
            exit("退款-SUCCESS");
        }else{
            exit("退款-FAIL");
        }
    }
    //支付宝退款
    public function alipay_refund($order_sn,$amount,$amount1){
        $config =  \addons\epay\library\Service::getConfig('alipay');
        vendor('aop.AopCertClient');
        vendor('aop.request.AlipayTradeRefundRequest');
        $aop = new \AopCertClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $config['app_id'];
        $aop->rsaPrivateKey = $config['private_key'];
        $aop->alipayrsaPublicKey = $config['ali_public_key'];
        $aop->alipayrsaPublicKey = $aop->getPublicKey($config['ali_public_key']);//调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $aop->appCertSN = $aop->getCertSN($config['app_cert_public_key']);//调用getCertSN获取证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($config['alipay_root_cert']);//调用getRootCertSN获取支付宝根证书序列号
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeRefundRequest ();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $request->setBizContent("{" .
            "\"out_trade_no\":\"{$order_sn}\"," .  //订单支付时传入的商户订单号,不能和 trade_no同时为空。 特殊可选
            "\"refund_amount\":\"{$amount}\"," . //需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数     必选
            "\"refund_reason\":\"订单取消-退款\"" . //退款的原因说明    正常退款 可选 最后的“，”逗号去掉
            "}");
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->execute ($request);
        //Log::record($response);
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $response->$responseNode;
        var_dump($resultCode);exit;
        if(!empty($resultCode) && $resultCode == 10000){
            return true;
        } else {
            return false;
        }

    }
}
